from django.shortcuts import render,HttpResponse,redirect
from django import forms
from myapp.utils.Bootstrap import BootstrapForm,BootstrapModelForm
from myapp import models
from myapp.utils.Pagination import Pagination

class uploadForm(BootstrapForm):
    exclude_list = ['head']
    name = forms.CharField(label='姓名',max_length=32)
    age = forms.IntegerField(label='年龄')
    head = forms.FileField(label="头像")

def upload_form(request):
    title = 'Form上传'
    if request.method =="GET":
        form = uploadForm()
        return render(request,'upload_form.html',{'form':form,'title':title})
    form = uploadForm(data=request.POST,files=request.FILES)
    # 把图片存在本地static/img文件里,把路径放到数据库
    img_obj = request.FILES.get("head")
    import os
    # path = 'static/img/{}'.format(img_obj.name)
    # 避免linux和window的分割符不同用os来拼接路径
    path = os.path.join('media',img_obj.name)
    with open(path,mode='wb') as file:
        for chunk in img_obj.chunks():
            file.write(chunk)
    if form.is_valid():
        models.Boss.objects.create(
            name=request.POST.get('name'),
            age = request.POST.get('age'),
            img= path
        )
        return HttpResponse('上传成功')
    return render(request, 'upload_form.html', {'form': form, 'title': title})



class uploadModelForm(BootstrapModelForm):
    exclude_list = ["img"]
    class Meta:
        model = models.City
        fields = "__all__"

def upload_modelform(request):
    if request.method =="GET":
        form = uploadModelForm()
        return render(request,'upload_form.html',{"form":form,"title":"modelForm上传"})
    form = uploadModelForm(data=request.POST,files=request.FILES)
    if form.is_valid():
        form.save()
        return redirect('/city/list')
    return render(request, 'change.html', {"form":form,"title":"modelForm上传"})

def city_list(request):
        query_set = models.City.objects.all()
        page_obj = Pagination(request,query_set=query_set)
        data_dict = {
            "departs":page_obj.data_queryset,
            "page_str":page_obj.html()
        }
        return render(request,"city_list.html", data_dict)
